<template>
  <div class="card" style="width: 60%; padding: 30px; margin: auto">
    <h3 style="text-align: center; margin-bottom: 20px">个人信息</h3>

    <el-form ref="formRef" :model="User.form" :rules="User.rules" label-width="120px">

      <!-- 账号 -->
      <el-form-item label="账号">
        <el-input v-model="User.form.username" disabled />
      </el-form-item>

      <!-- 姓名 -->
      <el-form-item label="姓名" prop="name">
        <el-input v-model="User.form.name" placeholder="请输入姓名" :disabled="!isEditing" />
      </el-form-item>

      <!-- 性别 -->
      <el-form-item label="性别" prop="sex">
        <el-select v-model="User.form.sex" placeholder="请选择性别" :disabled="!isEditing">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="User.form.email" placeholder="请输入邮箱" :disabled="!isEditing" />
      </el-form-item>

      <!-- 电话 -->
      <el-form-item label="电话" prop="telephone">
        <el-input v-model="User.form.telephone" placeholder="请输入电话" :disabled="!isEditing" />
      </el-form-item>

      <!-- 学校 -->
      <el-form-item label="学校" prop="school">
        <el-input v-model="User.form.school" placeholder="请输入所在学校" :disabled="!isEditing" />
      </el-form-item>

      <!-- 学历 -->
      <el-form-item label="学历" prop="record">
        <el-select v-model="User.form.record" placeholder="请选择学历" :disabled="!isEditing">
          <el-option label="专科" :value="0" />
          <el-option label="本科" :value="1" />
          <el-option label="硕士" :value="2" />
          <el-option label="博士" :value="3" />
        </el-select>
      </el-form-item>

      <!-- 薪资期望 -->
      <el-form-item label="薪资期望" prop="salary">
        <el-input-number v-model="User.form.salary" :min="0" :max="100000" label="请输入期望薪资" :disabled="!isEditing" />
      </el-form-item>

      <!-- 所在城市（支持多选） -->
      <el-form-item label="所在城市" prop="city">
        <el-select v-model="User.form.cityList" multiple placeholder="请选择城市" :disabled="!isEditing">
          <el-option
            v-for="item in cityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 福利待遇 -->
      <el-form-item label="福利待遇" prop="benefits">
        <el-input v-model="User.form.benefits" type="textarea" :rows="3" placeholder="请输入期望的福利待遇" :disabled="!isEditing" />
      </el-form-item>

      <!-- 办公时间（拆分成上下班） -->
      <el-form-item label="办公时间" prop="officeHours">
        <el-time-picker
          v-model="User.form.startTime"
          value-format="HH:mm"
          format="HH:mm"
          placeholder="开始时间"
          :disabled="!isEditing"
        />
        <span style="margin: 0 10px">至</span>
        <el-time-picker
          v-model="User.form.endTime"
          value-format="HH:mm"
          format="HH:mm"
          placeholder="结束时间"
          :disabled="!isEditing"
        />
      </el-form-item>

      <!-- 注册时间 -->
      <el-form-item label="注册时间">
        <el-input v-model="User.form.registerTime" disabled />
      </el-form-item>

      <!-- 最后更新时间 -->
      <el-form-item label="最后更新时间">
        <el-input v-model="User.form.updateTime" disabled />
      </el-form-item>

<!-- 按钮区域 -->
<el-form-item style="text-align: center">
  <el-button @click="toggleEdit" type="primary" v-if="!isEditing">修改信息</el-button>
  <el-button @click="updateUser" type="success" v-else>提交信息</el-button>
  <el-button @click="router.back()" plain>返回</el-button>
</el-form-item>


    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { parseJwt, getToken } from '@/utils/auth'

const formRef = ref()

// 城市选项（从后端获取或硬编码）
const cityOptions = [
  { label: '北京', value: '北京' },
  { label: '上海', value: '上海' },
  { label: '天津', value: '天津' },
  { label: '重庆', value: '重庆' },
  { label: '河北', value: '河北' },
  { label: '山西', value: '山西' },
  { label: '辽宁', value: '辽宁' },
  { label: '吉林', value: '吉林' },
  { label: '黑龙江', value: '黑龙江' },
  { label: '江苏', value: '江苏' },
  { label: '浙江', value: '浙江' },
  { label: '安徽', value: '安徽' },
  { label: '福建', value: '福建' },
  { label: '江西', value: '江西' },
  { label: '山东', value: '山东' },
  { label: '河南', value: '河南' },
  { label: '湖北', value: '湖北' },
  { label: '湖南', value: '湖南' },
  { label: '广东', value: '广东' },
  { label: '海南', value: '海南' },
  { label: '四川', value: '四川' },
  { label: '贵州', value: '贵州' },
  { label: '云南', value: '云南' },
  { label: '陕西', value: '陕西' },
  { label: '甘肃', value: '甘肃' },
  { label: '青海', value: '青海' },
  { label: '台湾', value: '台湾' },
  { label: '内蒙古', value: '内蒙古' },
  { label: '广西', value: '广西' },
  { label: '西藏', value: '西藏' },
  { label: '宁夏', value: '宁夏' },
  { label: '新疆', value: '新疆' },
  { label: '香港', value: '香港' },
  { label: '澳门', value: '澳门' }
];
// 学生信息（默认只读）
const User = reactive({
  form: {
    username: '',
    name: '',
    sex: '',
    email: '',
    telephone: '',
    school: '',
    record: null,
    salary: 0,
    cityList: [], // 支持多选
    benefits: '',
    startTime: '', // 上班时间
    endTime: '',   // 下班时间
    registerTime: '',
    updateTime: ''
  },
  rules: {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
    ],
    telephone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
    school: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
    record: [{ required: true, message: '请选择学历', trigger: 'change' }]
  }
})

// 使用 ref 控制编辑状态
const isEditing = ref(false)

// 模拟从 JWT 解析用户信息并加载数据
const loadUserInfo = () => {
  const token = getToken();
  if (!token) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }

  const userInfo = parseJwt(token);
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录');
    router.push('/login');
    return;
  }

  axios.get(`/api/student/info/${userInfo.id}`, {
    headers: {
      Authorization: 'Bearer ' + token
    }
  }).then(res => {
    if (res.status === 304) {
      const cachedData = JSON.parse(localStorage.getItem('cachedStudentData'));
      if (cachedData) {
        populateForm(cachedData);
      } else {
        ElMessage.error('缓存数据缺失，请刷新页面');
      }
    } else if (res.data && res.data.code === 200 && res.data.data) {
      populateForm(res.data.data);
      localStorage.setItem('cachedStudentData', JSON.stringify(res.data.data));
    } else {
      ElMessage.error('获取用户信息失败');
    }
  }).catch(err => {
    console.error('请求失败:', err);
    ElMessage.error('网络异常，请重试');
  });
};

const populateForm = (data) => {
  User.form.username = data.username;
  User.form.name = data.name;
  User.form.sex = data.sex;
  User.form.email = data.email;
  User.form.telephone = data.telephone;
  User.form.school = data.school;
  User.form.record = data.record;
  User.form.salary = data.salary;
  User.form.cityList = data.city ? data.city.split(',') : [];
  User.form.benefits = data.benefits;
  const officeHours = data.officeHours?.split(' - ');
  User.form.startTime = officeHours?.[0] || '';
  User.form.endTime = officeHours?.[1] || '';
  User.form.registerTime = formatDate(data.registerTime);
  User.form.updateTime = formatDate(data.updateTime);
};

// 切换编辑状态
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

// 更新用户信息
const updateUser = async () => {
  const userInfo = parseJwt()
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }

  const dataToSend = {
    id: userInfo.id,
    name: User.form.name,
    sex: User.form.sex,
    email: User.form.email,
    telephone: User.form.telephone,
    school: User.form.school,
    record: User.form.record,
    salary: User.form.salary,
    city: User.form.cityList.join(','), // 合并城市列表为字符串
    benefits: User.form.benefits,
    officeHours: `${User.form.startTime} - ${User.form.endTime}`
  }

  try {
    const res = await axios.put('http://localhost:8080/api/student/update', dataToSend, {
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('更新成功')
      localStorage.setItem('user', JSON.stringify(User.form))
      toggleEdit() // 返回只读模式
    } else {
      ElMessage.error(res.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('请求错误:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录状态异常，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('网络异常，请重试')
    }
  }
}

// 工具方法：统一日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return ''

  // 处理 LocalDateTime 字符串格式："2025-04-07T14:30:00"
  const date = new Date(dateStr)

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从 0 开始
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  loadUserInfo()
})

</script>

